﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SimpleMemberShip.Models;
using WebMatrix.WebData;
using System.Web.Security;
namespace SimpleMemberShip.Controllers
{
    public class AccountController : Controller
    {
        //
        // GET: /Account/
        [HttpGet]
        public ActionResult Login()
        {
            return View();
        }
        [HttpPost]        
        public ActionResult Login(Login logindata, string returnUrl)
        {
           if(ModelState.IsValid)
           {

               if (WebSecurity.Login(logindata.Username, logindata.Password))
               {
                   if (returnUrl != null)
                   {
                       return Redirect(returnUrl);
                   }
                   return RedirectToAction("Index", "Home");
               }
               else
               {
               ModelState.AddModelError("", "Username or password is invalid");
               return View(logindata);
               }
           }
             ModelState.AddModelError("", "Username or password is invalid");
             return View(logindata);
           
        }
        [HttpGet]
        public ActionResult Register()
        {
            return View();
        }
        [HttpPost]    
        [ValidateAntiForgeryToken]
        public ActionResult Register(Register registerdata, string role)
        {                    
           try 
	        {	        
		     if (ModelState.IsValid)
                {
                    WebSecurity.CreateUserAndAccount(registerdata.Username, registerdata.Password);
                    Roles.AddUserToRole(registerdata.Username, role);
                    return RedirectToAction("Index", "Home");
                }
	        }
	        catch (MembershipCreateUserException exception)
	        {
                ModelState.AddModelError("", "Username already exist");
                return View(registerdata); 
	        }
           ModelState.AddModelError("", "Username already exist");
           return View(registerdata);              
        }
        public ActionResult Logout() 
        {
            WebSecurity.Logout();
            return RedirectToAction("Index", "Home");
        }
	}
}